﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Templates_OurPeople_Default : BaseTemplatePage
{
    protected override void AttachEvents()
    {
        listFeeEarners.DataBound += new EventHandler(list_DataBound);
        listAdministrators.DataBound += new EventHandler(list_DataBound);
        dsFeeEarners.SelectData += new EventHandler<Acms.DataControls.SelectEventArgs<Acms.Bll.Post>>(dsFeeEarners_SelectData);
        dsAdmin.SelectData += new EventHandler<Acms.DataControls.SelectEventArgs<Acms.Bll.Post>>(dsAdmin_SelectData);
    }

    void list_DataBound(object sender, EventArgs e)
    {
        var title = ((ListView)sender).FindControl("litTitle") as Literal;
        if (title != null)
        {
            var childIndex = sender == listAdministrators ? 1 : 0;
            if (AcmsContext.CurrentPost != null && AcmsContext.CurrentPost.Children.Count >= 2)
            {
                title.Text = AcmsContext.CurrentPost.Children[childIndex].DisplayName;
            }
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DataBind();
        }
    }

    void dsAdmin_SelectData(object sender, Acms.DataControls.SelectEventArgs<Acms.Bll.Post> e)
    {
        if (AcmsContext.CurrentPost != null)
        {
            //admin
            var tmp = AcmsContext.CurrentPost.Children[1].Children;
            e.SetData(OrderBySurname(tmp));
        }
        else
        {
            e.SetData(Acms.Bll.DummyPost.CreateDummyList(48));
        }
    }

    void dsFeeEarners_SelectData(object sender, Acms.DataControls.SelectEventArgs<Acms.Bll.Post> e)
    {
        if (AcmsContext.CurrentPost != null)
        {
            //feeaernerrs
            var tmp = AcmsContext.CurrentPost.Children[0].Children;
            e.SetData(OrderBySurname(tmp));
        }
        else
        {
            e.SetData(Acms.Bll.DummyPost.CreateDummyList(48));
        }
    }

    private List<Acms.Bll.Post> OrderBySurname(List<Acms.Bll.Post> data)
    {
        return data.OrderBy(x =>
            x.DisplayName.Split(' ').Length >= 2 ? string.Format("{1}{0}", x.DisplayName.Split(' ')) : x.DisplayName)
            .ToList();
    }
}
